package com.zc.hadoop.mapreduce;

import java.io.IOException;
import java.util.StringTokenizer;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class WordCountMapReduce {
	// MapperClass
	// 以键值对的形式输入数据，与reduce对接的时候，同样以键值对形式对接
	public static class WordCountMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
		// 定义map输出key、value值
		protected Text mapOutputKey = new Text();
		// 以1开始计数
		protected IntWritable mapOutputValue = new IntWritable(1);

		// 输入端的key、value值
		protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
			// 获取每行数据
			String lineValue = value.toString();
			// 对每行数据分割
			StringTokenizer st = new StringTokenizer(lineValue);
			// 遍历值
			while (st.hasMoreTokens()) {
				// 获取每个值
				String wordValue = st.nextToken();
				// 设置map 输出的key值为单词
				mapOutputKey.set(wordValue);
				context.write(mapOutputKey, mapOutputValue);
			}
		}

	}

	// ReduceClass
	public static class WordCountReduce extends Reducer<Text, IntWritable, Text, IntWritable> {
		// 定义输出
		protected IntWritable outputValue = new IntWritable();

		protected void reduce(Text key, Iterable<IntWritable> values, Context context)
				throws IOException, InterruptedException {
			// 叠加
			int sum = 0;
			// 遍历IntWritable
			for (IntWritable value : values) {
				// 累加
				sum += value.get();
			}
			// 设置得到总次数
			outputValue.set(sum);
			context.write(key, outputValue);
		}

	}

	// 入口函数：Driver构建一个Job
	public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
		// 获取配置
		Configuration conf = new Configuration();
		
		// 设置job
		Job job = Job.getInstance(conf, WordCountMapReduce.class.getSimpleName());
		
		// 设置job运行类
		job.setJarByClass(WordCountMapReduce.class);
		
		// 数据的输入
		Path inputDir = new Path(args[0]);
		FileInputFormat.addInputPath(job, inputDir);
		
		// 设置mapper
		job.setMapperClass(WordCountMapper.class);
		job.setMapOutputKeyClass(Text.class);
		job.setMapOutputValueClass(IntWritable.class);
		
		// 设置reduce
		job.setReducerClass(WordCountReduce.class);
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(IntWritable.class);
		
		// 设置输出
		Path outputDir = new Path(args[1]);
		FileOutputFormat.setOutputPath(job, outputDir);

		// 提交job 等待运行结束 并在客户端显示运行信息
		boolean flag = job.waitForCompletion(true);
		System.exit(flag ? 0 : 1);
	}
}
